import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { isPathMatch } from '@/utils/validate'
import { getToken } from '@/utils/auth' // get token from cookie

NProgress.configure({ showSpinner: false }) // NProgress Configuration

const whiteList = ['/login'] // no redirect whitelist

const isWhiteList = (path) => {
  return whiteList.some((pattern) => isPathMatch(pattern, path))
}
let oneRun = true
router.beforeEach((to, from, next) => {
  NProgress.start()
  if (getToken()) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    /* has token*/
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else if (isWhiteList(to.path)) {
      next()
    } else {
      if (store.getters.permissionList.length !== 0 || !oneRun) {
        next()
        return
      }
      store
        .dispatch('user/getInfo')
        .then(() => {
          // 根据roles权限生成可访问的路由表
          router.addRoutes(store.getters.permissionList) // 动态添加可访问路由表
          router.options.routes = [...store.getters.permissionList]
          next({ ...to, replace: true }) // hack方法 确保addRoutes已完成
          NProgress.done()
        })
        .catch((err) => {
          store.dispatch('user/logout').then(() => {
            Message.error(err)
            next({ path: '/' })
          })
        })
    }
  } else {
    // 没有token
    if (isWhiteList(to.path)) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${encodeURIComponent(to.fullPath)}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
